package dao;

import java.sql.*;

import modle.Admin;
import modle.Customer;

//(throws Exception) : 在方法声明部分使用，表示该方法可能产生此异常，如果在方法声明处使用了throws声明异常，则该方法产生异常也不必捕获，会直接把异常抛出到调用该方法的地方。
public class AdminDao {
	
	//登录：从数据库中查询特定的admin的信息
	public static Admin login(Connection con,Admin user) throws Exception {
		Admin resultUser = null;
		
		//先预编译（编译的是sql语句的框架）后传值（? 是占位符，会自动加单引号）
		String sql = "select * from admin where UserName = ? and PassWord = ?";
		
		//表示（获取）预编译的SQL语句的对象。
		PreparedStatement pstmt = con.prepareStatement(sql);
		
		pstmt.setString(1, user.getUserName());
		pstmt.setString(2, user.getPassWord());
		ResultSet rs = pstmt.executeQuery();			//返回表的查询集合（应该是从上一个指针开始）
		
		if(rs.next()) {
			resultUser = new Admin();
			resultUser.setUserName(rs.getString("UserName"));
			resultUser.setPassWord(rs.getString("PassWord"));
			resultUser.setEmail(rs.getString("Email"));
			resultUser.setId(rs.getInt("Id"));
		}
		
		return resultUser;
	}
	
	public static int Add(Connection con,Admin user) throws Exception {
		
		String sql = "insert into `admin` values(?,?,?,null)";
		PreparedStatement pstmt = con.prepareStatement(sql);
		pstmt.setString(1, user.getUserName());
		pstmt.setString(2, user.getPassWord());
		pstmt.setString(3, user.getEmail());
		
		return pstmt.executeUpdate();
	}
	
	public static boolean isUserExist(Connection con, Admin user) throws Exception {
		// TODO Auto-generated method stub
		String sql="select * from admin where UserName=?";
		PreparedStatement pstmt=con.prepareStatement(sql);
		pstmt.setString(1, user.getUserName());
		ResultSet rs =pstmt.executeQuery();
		return rs.next();
	}
}
